package kr.or.smardi.smardi_AScan.Record;

import java.lang.reflect.*;
import java.text.*;
import java.util.*;

import kr.or.smardi.smardi_AScan.*;
import kr.or.smardi.smardi_AScan.Help.*;
import kr.or.smardi.smardi_AScan.Record.graph.*;
import kr.or.smardi.smardi_AScan.Scan.*;
import kr.or.smardi.smardi_AScan.User.*;
import kr.or.smardi.smardi_AScan.db.*;
import android.app.*;
import android.content.*;
import android.database.*;
import android.graphics.*;
import android.os.*;
import android.util.*;
import android.view.*;
import android.widget.*;
import android.widget.TableRow.LayoutParams;

public class AC_RecordMain extends Activity {
	private boolean D = false;
	String TAG = "A-SCAN";

	

	// TextView
	TextView txt_date;

	// TableLayout
	TableLayout table_resultList;

	// ScrollView
	ScrollView scrollResult;

	//상단 타이틀바
	RelativeLayout titleBar = null;
	ImageButton btn_TopLeft = null;
	ImageButton btn_TopRight = null;
	TextView txt_subTitle = null;
	
	//탭 메뉴
	LinearLayout tabMenu = null;
	ImageButton tab_measure = null;
	ImageButton tab_record = null;
	ImageButton tab_user = null;
	ImageButton tab_help = null;
	
	// 하단 버튼
	ImageView btn_daily_monthly, btn_date, btn_graph_chart;

	// 그래프 들어갈 자리
	LinearLayout graphLayout;

	DB_Adapter dbAdapter;

	// SharedPreference
	Manage_SharedPreference mPref;

	// 현재 어떤 모드로 데이터를 가져올 것인가에 대한 설정들
	private int displayInformationType = -1;
	private final int DISPLAY_LAST_30DAYS = 0; // 마지막 30일을 표시
	private final int DISPLAY_LAST_24HOURS = 4; // 마지막 24시간을 표시
	private final int DISPLAY_LAST_48HOURS = 1; // 마지막 24시간을 표시
	private final int DISPLAY_SPECIPIC_MONTH = 2; // 특정한 달을 표시
	private final int DISPLAY_SPECIPIC_DAY = 3; // 특정한 일을 표시

	// 사용자가 선택한 특정 날짜를 저장하기 위한 변수
	private int selectedYear = 0;
	private int selectedMonth = 0;
	private int selectedDay = 0;

	// 그래프 출력을 위한 설정들
	private int selectedUserUID = 0;
	private int selectedScanPlace = 0;
	private int selectedDateType = 0;

	private final int DATETYPE_MONTHLY = 0;
	private final int DATETYPE_DAYLY = 1;
	private String[] DATETYPE_ARRAY = null;

	private int selectedResultView = 1;
	private final int RESULTVIEW_CHART = 0;
	private final int RESULTVIEW_GRAPH = 1;

	// 테이블을 그린 결과 몇개의 데이터가 있는지 파악해서 그래프를 그릴지 판단하기 위함
	private int dataCount = 0;

	// 그래프가 이미 그려졌는지 판단하기 위함
	private boolean isDrawnGraph = false;

	// 화면 밀도
	DisplayMetrics outMetrics = new DisplayMetrics();

	long lastBackPressTime = 0;
	Toast toast;
	boolean isUserWantToExit = false;

	// Pause 상태에 들어갔는지
	boolean isPause = false;

	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.record_main);

		// 구성요소 초기화
		initComponents();

		// 선택된 시간을 현재로 초기화하기
		initSelectedTime();

		// 현재 시간을 표시하기
		displaySelectedTime();

		// 폰트 적용하기
		changeFont();

		// 이벤트 적용하기
		registButtonEvents();

		// 버튼에 들어갈 텍스트 초기화하기
		initText();

		// 데이터베이스에서 불러올 자료 초기화하기
		initData();

		// 보여질 결과(테이블/그래프) 선택
		// true: 테이블, false: 그래프
		changeResultView();

		getWindow().getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
		
		// 테이블과 그래프를 불러온다.
		displayInformationType = DISPLAY_LAST_30DAYS;
		loadData_from_Database_for_Table_and_Graph();
	}

	private void initData() {
		selectedUserUID = mPref.getUserUID();
		selectedScanPlace = mPref.getScanningPoint();
		selectedDateType = DATETYPE_MONTHLY;
	}

	private void initComponents() {
		DATETYPE_ARRAY = new String[] { getString(R.string.record_monthly),
				getString(R.string.record_dayly) };

		// SharedPreference
		mPref = new Manage_SharedPreference(AC_RecordMain.this);

		// Database
		dbAdapter = new DB_Adapter(AC_RecordMain.this);
		dbAdapter.open();

		// TextView
		txt_date = (TextView) findViewById(R.id.txt_date);

		// 하단 버튼들
		btn_daily_monthly = (ImageView) findViewById(R.id.btn_daily_monthly);
		btn_date = (ImageView) findViewById(R.id.btn_date);
		btn_graph_chart = (ImageView) findViewById(R.id.btn_graph_chart);

		// TableLayout
		table_resultList = (TableLayout) findViewById(R.id.table_resultList);

		// ScrollView
		scrollResult = (ScrollView) findViewById(R.id.scrollResult);

		// 그래프 들어갈 자리
		graphLayout = (LinearLayout) findViewById(R.id.graphList);

		
		//타이틀바 세팅
		titleBar = (RelativeLayout)findViewById(R.id.inc_title_bar);
		btn_TopLeft = (ImageButton)titleBar.findViewById(R.id.btn_top_left);
		btn_TopLeft.setImageDrawable(getResources().getDrawable(R.drawable.c_btn_back));
		btn_TopLeft.setOnClickListener(onClickListener);
		btn_TopRight = (ImageButton)titleBar.findViewById(R.id.btn_top_right);
		btn_TopRight.setVisibility(View.GONE);
		txt_subTitle = (TextView)findViewById(R.id.txt_subTitle);
		txt_subTitle.setText(getString(R.string.subTitle_scan_main));
		
		
		//탭 세팅--------------------------
		tabMenu = (LinearLayout)findViewById(R.id.inc_tab_menu);
		tab_measure = (ImageButton)findViewById(R.id.tab_measure);
		tab_record = (ImageButton)findViewById(R.id.tab_record);
		tab_record.setImageDrawable(getResources().getDrawable(R.drawable.tab_record_1));
		tab_user = (ImageButton)findViewById(R.id.tab_user);
		tab_help = (ImageButton)findViewById(R.id.tab_help);
		
		tab_record.setOnClickListener(onClickListener);
		tab_user.setOnClickListener(onClickListener);
		tab_help.setOnClickListener(onClickListener);
		//탭 세팅 끝--------------------------
	}

	@SuppressWarnings("static-access")
	private void initSelectedTime() {
		Calendar cal = Calendar.getInstance();
		selectedYear = cal.get(cal.YEAR);
		selectedMonth = cal.get(cal.MONTH) + 1;
		selectedDay = cal.get(cal.DATE);
	}

	private void displaySelectedTime() {
		switch (selectedDateType) {
		case DATETYPE_MONTHLY:

			txt_date.setText(selectedYear + "/" + selectedMonth);
			break;
		case DATETYPE_DAYLY:
			txt_date.setText(selectedYear + "/" + selectedMonth + "/"
					+ selectedDay);
			break;
		}
	}

	private void registButtonEvents() {
		btn_TopLeft.setOnClickListener(onClickListener);

		txt_date.setOnClickListener(onClickListener);

		txt_date.setOnClickListener(onClickListener);

		tab_measure.setOnClickListener(onClickListener);
		tab_help.setOnClickListener(onClickListener);
		tab_user.setOnClickListener(onClickListener);

		// 하단 버튼들
		btn_daily_monthly.setOnClickListener(onClickListener);
		btn_date.setOnClickListener(onClickListener);
		btn_graph_chart.setOnClickListener(onClickListener);
	}

	private void initText() {

		txt_subTitle.setText(mPref.getUserName());
		txt_date.setText(getString(R.string.record_monthly));
	}

	/**
	 * 테이블과 그래프를 그리기 위해 DB에서 데이터를 불러오고 테이블을 작성하고 그래프를 그린다.
	 */
	private void loadData_from_Database_for_Table_and_Graph() {

		displaySelectedTime(); // 현재 시간으로 초기화

		Cursor cursor = null;

		switch (displayInformationType) {
		case DISPLAY_LAST_30DAYS:
			cursor = dbAdapter
					.fetchAllRecordByUserAndScanningPointLast30days(selectedUserUID);
			break;
		case DISPLAY_LAST_48HOURS:
			cursor = dbAdapter
					.fetchAllRecordByUserAndScanningPointLast48hours(selectedUserUID);
			break;
		case DISPLAY_LAST_24HOURS:
			cursor = dbAdapter
					.fetchAllRecordByUserAndScanningPointLast24hours(selectedUserUID);
			break;
		case DISPLAY_SPECIPIC_MONTH:
			cursor = dbAdapter.fetchAllRecordByUserAndScanningPointAtSomeMonth(
					selectedUserUID, selectedYear, selectedMonth);
			break;
		case DISPLAY_SPECIPIC_DAY:
			cursor = dbAdapter.fetchAllRecordByUserAtDay(selectedUserUID,
					selectedYear, selectedMonth, selectedDay);
			break;
		}

		loadTable(cursor);

		switch (displayInformationType) {
		case DISPLAY_LAST_30DAYS:
			cursor = dbAdapter
					.fetchAllRecordByUserAndScanningPointLast30days(selectedUserUID);
			break;
		case DISPLAY_LAST_24HOURS:
			cursor = dbAdapter
					.fetchAllRecordByUserAndScanningPointLast24hours(selectedUserUID);
			break;
		case DISPLAY_LAST_48HOURS:
			cursor = dbAdapter
					.fetchAllRecordByUserAndScanningPointLast48hours(selectedUserUID);
			break;
		case DISPLAY_SPECIPIC_MONTH:
			cursor = dbAdapter.fetchAllRecordByUserAndScanningPointAtSomeMonth(
					selectedUserUID, selectedYear, selectedMonth);
			break;
		case DISPLAY_SPECIPIC_DAY:
			cursor = dbAdapter.fetchAllRecordByUserAtDay(selectedUserUID,
					selectedYear, selectedMonth, selectedDay);
			break;
		}

		drawMyGraph(2000, 200, Float.NEGATIVE_INFINITY,
				Float.POSITIVE_INFINITY, 0, 0.2f, null, null, null, cursor);
	}

	View.OnClickListener onClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			// ---------------------------------------
			case R.id.btn_top_left:
				gotoScanMain();
				break;
			// ---------------------------------------
			case R.id.txt_date:
			case R.id.btn_date:
				try {
					DatePickerDialog datePickerDialog = new DatePickerDialog(
							AC_RecordMain.this, onDateSetListener,
							selectedYear, selectedMonth - 1, selectedDay);

					if (selectedDateType == DATETYPE_MONTHLY) {
						// 월간 데이터를 선택 할 때에는 월까지만 표시한다.

						Field[] f = datePickerDialog.getClass()
								.getDeclaredFields();
						for (Field dateField : f) {
							if (dateField.getName().equals("mDatePicker")) {
								dateField.setAccessible(true);

								DatePicker datePicker = (DatePicker) dateField
										.get(datePickerDialog);

								Field datePickerFields[] = dateField.getType()
										.getDeclaredFields();

								for (Field datePickerField : datePickerFields) {
									if ("mDayPicker".equals(datePickerField
											.getName())
											|| "mDaySpinner"
													.equals(datePickerField
															.getName())) {
										datePickerField.setAccessible(true);
										Object dayPicker = new Object();
										dayPicker = datePickerField
												.get(datePicker);
										((View) dayPicker)
												.setVisibility(View.GONE);
									}
								}
							}
						}
					} else {
						// 일간 데이터를 선택 할 때에는 날짜를 일까지 표시한다.
					}

					datePickerDialog.show();

				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
				break;
			// ---------------------------------------

			case R.id.btn_graph_chart:
				switch (selectedResultView) {
				case RESULTVIEW_CHART:
					selectedResultView = RESULTVIEW_GRAPH;
					break;
				case RESULTVIEW_GRAPH:
					selectedResultView = RESULTVIEW_CHART;
					break;
				}
				changeResultView();
				break;
			// ---------------------------------------
			case R.id.btn_daily_monthly:
				changeDateType();
				break;
			// ---------------------------------------
			case R.id.tab_measure:
				gotoScanMain();
				break;
			case R.id.tab_user:
				gotoUserMain();
				break;
			case R.id.tab_help:
				gotoHelpMain();
				break;
			}
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			gotoScanMain();
			return false;
			// return exitApp();
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 그래프의 날짜를 선택했을 때 이벤트 처리
	 */
	DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {

			selectedYear = year;
			selectedMonth = monthOfYear + 1;
			selectedDay = dayOfMonth;

			switch (displayInformationType) {
			case DISPLAY_LAST_30DAYS:
			case DISPLAY_SPECIPIC_MONTH:
				displayInformationType = DISPLAY_SPECIPIC_MONTH;
				break;
			case DISPLAY_LAST_24HOURS:
			case DISPLAY_LAST_48HOURS:
			case DISPLAY_SPECIPIC_DAY:
				displayInformationType = DISPLAY_SPECIPIC_DAY;
				break;
			}

			loadData_from_Database_for_Table_and_Graph();
		}
	};

	protected void changeDateType() {
		switch (selectedDateType) {
		case DATETYPE_DAYLY:
			selectedDateType = DATETYPE_MONTHLY;
			displayInformationType = DISPLAY_LAST_30DAYS;
			btn_daily_monthly.setImageDrawable(getResources().getDrawable(
					R.drawable.c_btn_record_monthly));
			break;
		case DATETYPE_MONTHLY:
			selectedDateType = DATETYPE_DAYLY;
			//displayInformationType = DISPLAY_LAST_48HOURS;
			displayInformationType = DISPLAY_LAST_24HOURS;
			btn_daily_monthly.setImageDrawable(getResources().getDrawable(
					R.drawable.c_btn_record_daily));
			break;
		}

		initSelectedTime();
		loadData_from_Database_for_Table_and_Graph();
	}

	/**
	 * 그래프를 나타내거나 차트를 나타낸다.
	 */
	protected void changeResultView() {
		switch (selectedResultView) {
		case RESULTVIEW_CHART: // 테이블 출력
			scrollResult.setVisibility(View.VISIBLE);
			graphLayout.setVisibility(View.GONE);
			btn_graph_chart.setImageDrawable(getResources().getDrawable(
					R.drawable.c_btn_record_chart));
			break;
		case RESULTVIEW_GRAPH: // 그래프 출력
			scrollResult.setVisibility(View.GONE);
			graphLayout.setVisibility(View.VISIBLE);
			btn_graph_chart.setImageDrawable(getResources().getDrawable(
					R.drawable.c_btn_record_graph));
			break;
		}
	}


	// --------------------------------------------------------------------------------
	// 테이블 작성
	private void loadTable(Cursor cursor) {
		SimpleDateFormat format_table = new SimpleDateFormat("MM-dd HH:mm");

		// 화면 밀도를 가져온다.
		getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
		float density = outMetrics.density;

		// 테이블 지우기
		table_resultList.removeAllViews();

		// 테이블 맨 위줄 입력
		TableRow tr = new TableRow(AC_RecordMain.this);
		TextView tv0 = new TextView(AC_RecordMain.this);
		TextView tv1 = new TextView(AC_RecordMain.this);

		int oldDataCount = 0; // 모든 시간에 대해서 데이터가 없는지 확인하기 위한 용도

		while (cursor.moveToNext()) {
			CellDataSet cellDataSet = new CellDataSet();
			cellDataSet.setUID(cursor.getLong(cursor.getColumnIndex("uid")));
			
			// Horizontal 리니어 레이아웃 작성
			tr = new TableRow(AC_RecordMain.this);
			tr.setGravity(Gravity.CENTER);
			// tr.setBackgroundDrawable(getResources().getDrawable(R.drawable.table_mid));
			tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
					LayoutParams.WRAP_CONTENT));
			
			// 각 셀 추가
			tv0 = new TextView(AC_RecordMain.this);
			String cellDate =format_table.format(new Date(cursor.getLong(2)));
			cellDataSet.setDate(cellDate);
			tv0.setText(cellDate);
			tv0.setGravity(Gravity.CENTER);
			tv0.setTextColor(Color.BLACK);
			// tv0.setBackgroundDrawable(getResources().getDrawable(R.drawable.table_mid_left));
			tv0.setLayoutParams(new LayoutParams((int) (density * 129.2525),
					(int) (density * 29.98125)));
			tv0.setTypeface(getFontDaum());

			double result = cursor.getDouble(1);
			String resultText = String.format("%.3f", Math.round(result*1000.)/1000.);
			cellDataSet.setValue(resultText);
			
			tv1 = new TextView(AC_RecordMain.this);
			tv1.setText(resultText + "%");
			tv1.setGravity(Gravity.CENTER);
			tv1.setTextColor(Color.BLACK);
			// tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.table_mid_right));
			tv1.setLayoutParams(new LayoutParams((int) (density * 102.6025),
					(int) (density * 29.98125)));
			tv1.setTypeface(getFontDaum());

			tr.addView(tv0);
			tr.addView(tv1);
			
			//Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.dash_line_bottom);
			tr.setBackgroundResource(R.drawable.dash_line_bottom);
			tr.setPadding(0, DPtoPX(8), 0, 0);
			

			table_resultList.addView(tr, new TableLayout.LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
			
			//이벤트 등록
			tr.setTag(cellDataSet);
			tr.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					deleteData((CellDataSet)v.getTag());
				}
			});
		}

		// 데이터가 하나도 없을 경우
		dataCount = cursor.getCount();

		if (oldDataCount < dataCount) {
			oldDataCount = dataCount;
		}

		dataCount = oldDataCount;

		if (oldDataCount == 0) {
			dataCount = 0;
			// Horizontal 리니어 레이아웃 작성
			tr = new TableRow(AC_RecordMain.this);
			tr.setGravity(Gravity.CENTER);
			// tr.setBackgroundDrawable(getResources().getDrawable(R.drawable.table_mid));
			tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
					LayoutParams.WRAP_CONTENT));

			// 각 셀 추가
			tv0 = new TextView(AC_RecordMain.this);
			tv0.setText("None");
			tv0.setGravity(Gravity.CENTER);
			tv0.setTextColor(Color.BLACK);
			// tv0.setBackgroundDrawable(getResources().getDrawable(R.drawable.table_mid_left));
			tv0.setLayoutParams(new LayoutParams((int) (density * 129.2525),
					(int) (density * 29.98125)));
			tv0.setTypeface(getFontDaum());

			tv1 = new TextView(AC_RecordMain.this);
			tv1.setText("None");
			tv1.setGravity(Gravity.CENTER);
			tv1.setTextColor(Color.BLACK);
			// tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.table_mid_right));
			tv1.setLayoutParams(new LayoutParams((int) (density * 102.6025),
					(int) (density * 29.98125)));
			tv1.setTypeface(getFontDaum());

			tr.addView(tv0);
			tr.addView(tv1);

			table_resultList.addView(tr, new TableLayout.LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		}

	}
	
	class CellDataSet {
		String date = "";
		String value = "";
		long uid = 0;
		
		public CellDataSet() {
			
		}
		
		public CellDataSet(String _date, String _value, long _uid) {
			date = _date;
			value = _value;
			uid = _uid;
		}
		
		public void setDate(String _date) {
			date = _date;
		}
		
		public void setValue(String _value) {
			value = _value;
		}
		
		public void setUID(long _uid) {
			uid = _uid;
		}
		
		public String getDate() {
			return date;
		}
		
		public String getValue() {
			return value;
		}
		
		public long getUID() {
			return uid;
		}
	}

	protected void deleteData(final CellDataSet cellDataSet) {
		AlertDialog.Builder alert = new AlertDialog.Builder(AC_RecordMain.this);
		alert.setTitle("기록 삭제");
		String message = ("날짜: "+cellDataSet.getDate() + "\n");
		message += ("값: "+cellDataSet.getValue() + "%\n\n");
		message += ("삭제 하시겠습니까?");
		alert.setMessage(message);
		
		alert.setPositiveButton(getString(R.string.dialog_Delete), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dbAdapter.deleteRecord(cellDataSet.getUID());
				loadData_from_Database_for_Table_and_Graph();
			}
		});
		alert.setNegativeButton(getString(R.string.dialog_Cancel), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		alert.show();
	}

	// =======================================
	// 내가 작성한 그래프 그리기
	@SuppressWarnings("static-access")
	private void drawMyGraph(int width, int height, float minX, float maxX,
			float minY, float maxY, ArrayList<ArrayList<float[]>> datas,
			ArrayList<Integer> colors, ArrayList<String> titles, Cursor cursor) {

		graphLayout.removeAllViews();
		/*
		 * RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)
		 * graphLayout .getLayoutParams();
		 * 
		 * HorizontalScrollView scrollViewB = new HorizontalScrollView(
		 * AC_RecordMain.this); // scrollViewB.setLayoutParams(new //
		 * LayoutParams(LayoutParams.FILL_PARENT, //
		 * (int)(height*outMetrics.density))); scrollViewB.setLayoutParams(new
		 * LayoutParams(LayoutParams.FILL_PARENT,
		 * TableRow.LayoutParams.FILL_PARENT));
		 * scrollViewB.setFadingEdgeLength(0); graphLayout.addView(scrollViewB);
		 * 
		 * LinearLayout linearLayout = new LinearLayout(AC_RecordMain.this);
		 * linearLayout.setLayoutParams(new LayoutParams( (int) (width *
		 * outMetrics.density), LayoutParams.WRAP_CONTENT));
		 * linearLayout.setLayoutParams(new LayoutParams( (int) (width *
		 * outMetrics.density), LayoutParams.WRAP_CONTENT));
		 * linearLayout.setOrientation(LinearLayout.HORIZONTAL);
		 * linearLayout.setPadding(0, 0, 0, 0);
		 * scrollViewB.addView(linearLayout);
		 */

		// Data 넣기
		long startTimestamp = 0;
		long endTimestamp = 0;
		Date now = new Date();

		GregorianCalendar cal = new GregorianCalendar(selectedYear,
				selectedMonth - 1, 1);
		int maxDay = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);

		int dataMode = -1;
		final int DATAMODE_DAY = 0;
		final int DATAMODE_10MIN = 1;
		final int DATAMODE_1HOUR = 2;

		switch (displayInformationType) {
		case DISPLAY_LAST_30DAYS:
			endTimestamp = new Date(now.getYear(), now.getMonth(),
					now.getDate(), 23, 59, 59).getTime() + 999;
			startTimestamp = endTimestamp - (long) 30 * (long) 24 * (long) 60
					* (long) 60 * (long) 1000 + 1;
			dataMode = DATAMODE_DAY;
			break;
		case DISPLAY_SPECIPIC_MONTH:
			startTimestamp = new Date(selectedYear - 1900, selectedMonth - 1, 1)
					.getTime();
			endTimestamp = new Date(selectedYear - 1900, selectedMonth - 1,
					maxDay, 23, 59, 59).getTime() + 1000;
			dataMode = DATAMODE_DAY;
			break;
		case DISPLAY_LAST_24HOURS:
			endTimestamp = new Date(now.getYear(), now.getMonth(),
					now.getDate(), now.getHours() + 1, 0, 0).getTime() - 1;
			startTimestamp = endTimestamp - (long) 24 * (long) 60 * (long) 60
					* (long) 1000 + 1;
			dataMode = DATAMODE_1HOUR;
			break;
		case DISPLAY_SPECIPIC_DAY:
			startTimestamp = new Date(selectedYear - 1900, selectedMonth - 1,
					selectedDay, 0, 0, 0).getTime();
			endTimestamp = new Date(selectedYear - 1900, selectedMonth - 1,
					selectedDay + 1, 0, 0, 0).getTime() - 1;
			dataMode = DATAMODE_1HOUR;
			break;
		}
		
		if(D) {
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			Log.e(TAG, "startTime:"+startTimestamp+" ("+ formatter.format(new Date(startTimestamp))+")");
			Log.e(TAG, "endTime:"+endTimestamp+" ("+formatter.format(new Date(endTimestamp))+")");
			
		}

		long term = 0;
		int graphWidth = 0;

		switch (dataMode) {
		case DATAMODE_DAY:
			term = 24 * 60 * 60 * 1000; // 1일
			break;
		case DATAMODE_10MIN:
			term = 10 * 60 * 1000; // 10분
			break;
		case DATAMODE_1HOUR:
			term = 60 * 60 * 1000;
			break;
		}

		graphWidth = graphLayout.getMeasuredWidth();

		RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)graphLayout.getLayoutParams();
		
		
		MyView myView = new MyView(AC_RecordMain.this, getWindow(),
				graphLayout.getMeasuredWidth(),
				graphLayout.getMeasuredHeight(), minX, maxX, minY, maxY);
		
		// myView.setLayoutParams(new
		// LayoutParams(Math.round(width*outMetrics.density),
		// Math.round(height*outMetrics.density)));

		myView.setLayoutParams(new LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.FILL_PARENT));

		switch (dataMode) {
		case DATAMODE_DAY:
			myView.setXUnit(MyView.UNIT_DAY);
			break;
		case DATAMODE_10MIN:
			myView.setXUnit(MyView.UNIT_10MIN);
			break;
		case DATAMODE_1HOUR:
			myView.setXUnit(MyView.UNIT_10MIN);
			break;
		}

		// 데데이터베이스에서 데이터 뽑아내기
		ArrayList<databaseData> dataList = new ArrayList<databaseData>();

		while (cursor.moveToNext()) {
			databaseData tempData = new databaseData();

			tempData.setTime(cursor.getLong(cursor.getColumnIndex("scan_time")));
			double value = cursor.getDouble(cursor.getColumnIndex("scan_value"));
			tempData.setValue(value);

			dataList.add(tempData);
		}

		// 시간별로 데이터 생성
		// 예) 월별 : 일별로 평균 값 생성
		int indexOfDatalist = 0;
		myView.makeGraphData();

		// Term으로 나누는 것은 그래프에 표기하기 어려움
		for (long i = 0; startTimestamp + i * term < endTimestamp; i++) {
			
			long start = startTimestamp + i * term;
			long end = startTimestamp + (i + 1) * term;
			double maxValue = Double.NEGATIVE_INFINITY;
			
			//start에서 end까지의 최대값을 구한다.
			if(dataList.size() > 0
					&& start <= dataList.get(indexOfDatalist).getTime() 
					&& dataList.get(indexOfDatalist).getTime() < end) {
				//데이터의 indexOfDatalist 번째 시간이 start와 end 사이에 있을 때
				
				for (int j = indexOfDatalist; j < dataList.size(); j++) {
					if(dataList.get(j).getTime() < end) {
						if(maxValue < dataList.get(j).getValue()) {
							maxValue = dataList.get(j).getValue(); 
						}
					} else {
						//j번째에서 end까지의 범위를 벗어났음
						indexOfDatalist = j;
						break;
					}
					
					if(j == dataList.size() - 1) {
						indexOfDatalist = j;
					}
				}
				
				if(D) {
					Log.e(TAG, "dataList.size:"+dataList.size());
					Log.e(TAG, "indexOfDatalist:"+indexOfDatalist);
				}
			} else {
				//start와 end 사이에 값이 없을 경우 0으로 설정한다.
				maxValue = 0;
			}
			
			
			myView.addGraphData((start + end)/2, maxValue);
			
		}
		
		
		
		myView.saveGraphData(Color.GRAY, "");

		graphLayout.addView(myView);
	}

	/**
	 * 데이터베이스에서 불러온 데이터를 시간/값으로 저장함
	 * 
	 * @author floro
	 * 
	 */
	private class databaseData {

		private long time = 0;
		private double value = 0;

		public databaseData() {
			this.time = 0;
			this.value = 0;
		}

		@SuppressWarnings("unused")
		public databaseData(long time, int value) {
			this.time = time;
			this.value = value;
		}

		public long getTime() {
			return time;
		}

		public double getValue() {
			return value;
		}

		public void setTime(long time) {
			this.time = time;
		}

		public void setValue(double d) {
			this.value = d;
		}
	}

	// =======================================
	private void gotoScanMain() {
		Intent intent = new Intent(AC_RecordMain.this, AC_Scan_main.class);
		startActivity(intent);
		finish();
		overridePendingTransition(R.anim.fadein, R.anim.fadeout);
	}

	private void gotoUserMain() {
		Intent intent = new Intent(AC_RecordMain.this, AC_UserMain.class);
		startActivity(intent);
		finish();
		overridePendingTransition(R.anim.fadein, R.anim.fadeout);
	}

	private void gotoHelpMain() {
		Intent intent = new Intent(AC_RecordMain.this, AC_Help_main.class);
		startActivity(intent);
		finish();
		overridePendingTransition(R.anim.fadein, R.anim.fadeout);
	}

	@Override
	protected void onPause() {
		super.onPause();

		isPause = true;
	}

	@Override
	protected void onResume() {
		super.onResume();

		if (isPause == true) {
			Intent intent = getIntent();
			finish();
			startActivity(intent);
			isPause = false;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		dbAdapter.close();
		if (isUserWantToExit == true) {
			moveTaskToBack(true);
			android.os.Process.killProcess(android.os.Process.myPid());
		}
	}

	private void changeFont() {
		Typeface tf = Typeface.createFromAsset(getAssets(),
				"fonts/Daum_Regular.ttf");

		txt_date.setTypeface(tf);
		txt_subTitle.setTypeface(tf);
	}

	private Typeface getFontDaum() {
		return Typeface.createFromAsset(getAssets(), "fonts/Daum_Regular.ttf");
	}

	@SuppressWarnings("unused")
	private int convertDPtoPX(double dp) {
		DisplayMetrics outMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(outMetrics);

		return (int) (dp * outMetrics.density + 0.5f);
	}

	@SuppressWarnings("unused")
	private long getTimestamp(String _date) {
		try {
			SimpleDateFormat formatter = new SimpleDateFormat(
					"yyyy-MM-dd hh:mm:ss");
			Date date = (Date) formatter.parse(_date);

			return date.getTime();
		} catch (ParseException e) {
			e.printStackTrace();
			return 0;
		}
	}

	
	public int DPtoPX(float dp) {
		return Math.round(outMetrics.density * dp);
	}
}
